package sf.lambda;

import sf.database.meta.ColumnMapping;
import sf.database.meta.MetaHolder;
import sf.database.meta.TableMapping;
import sf.tools.StringUtils;

import java.lang.invoke.SerializedLambda;
import java.lang.reflect.Method;

public class LambdaHelp {
    public static <T> String getFunctionName(Property<T, ?> property, Class<?> clazz) {
        try {
            Method declaredMethod = property.getClass().getDeclaredMethod("writeReplace");
            declaredMethod.setAccessible(Boolean.TRUE);
            SerializedLambda serializedLambda = (SerializedLambda) declaredMethod.invoke(property);
            String method = serializedLambda.getImplMethodName();
            String attr = null;
            if (method.startsWith("get")) {
                attr = method.substring(3);
            } else {
                attr = method.substring(2);
            }
            TableMapping tm = MetaHolder.getMeta(clazz);
            ColumnMapping cm = tm.getJavaFieldColumnMapping(StringUtils.firstCharToLowerCase(attr));
            if (cm != null) {
                return cm.getRawColumnName();
            }
            return null;
        } catch (ReflectiveOperationException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> String[] getFunctionName(Class<?> clazz, Property<T, ?>... funs) {
        String[] cols = new String[funs.length];
        int i = 0;
        for (Property<T, ?> property : funs) {
            cols[i++] = getFunctionName(property, clazz);
        }
        return cols;
    }
}
